package controllers

import (
	"gdshop-admin-go-api/app/request/BaseReq"
	"gdshop-admin-go-api/app/service/BaseService"
	"gdshop-admin-go-api/library/response"
	"github.com/gogf/gf/net/ghttp"
	"github.com/gogf/gf/util/gvalid"
)

type BaseController struct {
	Req *BaseReq.I
}

func (c *BaseController) GetReq() *BaseReq.I {
	return c.Req
}

func (c *BaseController) SetReq(req *BaseReq.I) {
	c.Req = req
}

func (c *BaseController) checkId(r *ghttp.Request) error {
	c.Req.Id = r.GetString("id", "")
	if err := gvalid.CheckValue(nil, c.Req.Id, "required", "ID不能为空"); err != nil {
		return err
	}

	return nil
}
func (c *BaseController) checkIds(r *ghttp.Request) error {
	//c.Req.Id = r.GetString("ids", "")
	c.Req.Ids = r.GetArray("ids")
	//fmt.Println(c.Req.Ids)
	//if err := gvalid.Check(c.Req.Id, "required", "IDS不能为空"); err != nil {
	//	return err
	//}
	//c.Req.Ids = strings.Split(strings.Trim(c.Req.Id, ","), ",")

	return nil
}

func (c *BaseController) Init(r *ghttp.Request) *response.JsonResponse {
	return response.SuccessByRequest(r)
}

func (c *BaseController) Shut(r *ghttp.Request) *response.JsonResponse {
	return response.SuccessByRequest(r)
}

func (c *BaseController) List(r *ghttp.Request) *response.JsonResponse {
	return BaseService.List(r, c.Req)
}

func (c *BaseController) Page(r *ghttp.Request) *response.JsonResponse {
	if err := r.Parse(&c.Req.PageInfo); err != nil {
		return response.FailByRequestMessage(r, err.Error())
	}
	return BaseService.Page(r, c.Req)
}

func (c *BaseController) Info(r *ghttp.Request) *response.JsonResponse {
	if err := c.checkId(r); err != nil {
		return response.FailByRequestMessage(nil, err.Error())
	}
	return BaseService.Info(r.GetCtx(), c.Req)
}

func (c *BaseController) Update(r *ghttp.Request) *response.JsonResponse {
	if c.Req.UpdateReq != nil {
		if err := r.Parse(c.Req.UpdateReq); err != nil {
			return response.FailByRequestMessage(r, err.Error())
		}
	}
	if err := c.checkId(r); err != nil {
		return response.FailByRequestMessage(nil, err.Error())
	}
	return BaseService.Update(r, c.Req)
}

func (c *BaseController) Delete(r *ghttp.Request) *response.JsonResponse {
	if err := c.checkIds(r); err != nil {
		return response.FailByRequestMessage(nil, err.Error())
	}
	return BaseService.Delete(r, c.Req)
}
func (c *BaseController) Add(r *ghttp.Request) *response.JsonResponse {
	if c.Req.AddReq != nil {
		if err := r.Parse(c.Req.AddReq); err != nil {
			return response.FailByRequestMessage(r, err.Error())
		}
	}
	return BaseService.Add(r, c.Req)
}
